<template>
  <div class="app-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon weekly">
              <i class="el-icon-date"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ weeklyCount > 0 ? weeklyCount : totalWeeklyCount }}</div>
              <div class="stats-label">
                {{ weeklyCount > 0 ? '本周周报' : '总周报数' }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon monthly">
              <i class="el-icon-time" style="color: white !important; font-size: 24px !important;"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ monthlyCount > 0 ? monthlyCount : totalMonthlyCount }}</div>
              <div class="stats-label">
                {{ monthlyCount > 0 ? '本月月报' : '总月报数' }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon materials">
              <i class="el-icon-document"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ materialsCount }}</div>
              <div class="stats-label">素材总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon templates">
              <i class="el-icon-files"></i>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ templates.length }}</div>
              <div class="stats-label">可用模板</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-card class="main-card" shadow="hover">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-edit-outline"></i>
          <span class="header-title">智能报告生成器</span>
          <el-tag
            :type="reportForm.type === 'weekly' ? 'primary' : 'success'"
            size="small"
          >
            {{ reportForm.type === "weekly" ? "周报模式" : "月报模式" }}
          </el-tag>
        </div>
        <div class="header-actions">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              @click="collectMaterials"
              :loading="collecting"
              icon="el-icon-magic-stick"
            >
              智能收集素材
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="generateDraft"
              :loading="generating"
              icon="el-icon-edit"
            >
              生成初稿
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="previewReport"
              :disabled="!generatedReport"
              icon="el-icon-view"
            >
              预览报告
            </el-button>
          </el-button-group>
        </div>
      </div>

      <el-tabs v-model="activeTab" type="border-card" class="custom-tabs">
        <!-- 报告配置 -->
        <el-tab-pane label="报告配置" name="config">
          <div class="config-container">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form
                  :model="reportForm"
                  label-width="100px"
                  class="config-form"
                >
                  <el-form-item label="报告类型" required>
                    <el-radio-group
                      v-model="reportForm.type"
                      @change="onTypeChange"
                    >
                      <el-radio-button label="weekly">
                        <i class="el-icon-date"></i> 周报
                      </el-radio-button>
                      <el-radio-button label="monthly">
                        <i class="el-icon-calendar"></i> 月报
                      </el-radio-button>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="日期范围" required>
                    <el-date-picker
                      v-model="reportForm.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-form-item>

                  <el-form-item label="报告模板" required>
                    <el-select
                      v-model="reportForm.template"
                      placeholder="请选择模板"
                      style="width: 100%"
                      filterable
                    >
                      <el-option
                        v-for="template in templates"
                        :key="template.templateId"
                        :label="template.templateName"
                        :value="template.templateId"
                      >
                        <div class="template-option">
                          <div class="template-name">
                            {{ template.templateName }}
                          </div>
                          <div class="template-desc">
                            {{ template.preview }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="报告标题">
                    <el-input
                      v-model="reportForm.title"
                      placeholder="请输入报告标题（可选）"
                      maxlength="100"
                      show-word-limit
                    ></el-input>
                  </el-form-item>
                </el-form>
              </el-col>

              <el-col :span="12">
                <div class="advanced-config">
                  <h4><i class="el-icon-setting"></i> 高级配置</h4>

                  <!-- 知识库统计信息 -->
                  <div class="kb-stats-card" v-if="knowledgeBases.length > 0">
                    <div class="kb-stats-header">
                      <div class="kb-stats-title">
                        <i class="el-icon-folder"></i>
                        <span>知识库统计</span>
                      </div>
                      <el-button
                        size="mini"
                        type="primary"
                        plain
                        icon="el-icon-refresh"
                        @click="loadKnowledgeBases"
                        :loading="loadingKnowledgeBases"
                        class="refresh-btn"
                      >
                        刷新
                      </el-button>
                    </div>
                    <div class="kb-stats-content">
                      <div class="kb-stat-item">
                        <span class="stat-label">总知识库:</span>
                        <span class="stat-value"
                          >{{ knowledgeBases.length }}个</span
                        >
                      </div>
                      <div class="kb-stat-item">
                        <span class="stat-label">总文档:</span>
                        <span class="stat-value">{{ totalKbDocuments }}个</span>
                      </div>
                      <div class="kb-stat-item">
                        <span class="stat-label">已选择:</span>
                        <span class="stat-value"
                          >{{
                            advancedForm.selectedKnowledgeBases.length
                          }}个</span
                        >
                      </div>
                    </div>
                  </div>

                  <el-form :model="advancedForm" label-width="100px">
                    <el-form-item label="查询关键词" required>
                      <el-input
                        v-model="advancedForm.kbQuery"
                        placeholder="请输入要查询的关键词"
                        maxlength="50"
                        show-word-limit
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="选择知识库">
                      <div class="kb-select-container">
                        <div class="kb-select-header">
                          <span class="kb-select-title"
                            >选择要查询的知识库</span
                          >
                          <div class="kb-select-actions">
                            <el-button
                              size="mini"
                              type="primary"
                              plain
                              @click="selectAllKnowledgeBases"
                              icon="el-icon-check"
                            >
                              全选
                            </el-button>
                            <el-button
                              size="mini"
                              type="danger"
                              plain
                              @click="clearKnowledgeBases"
                              icon="el-icon-delete"
                            >
                              清空
                            </el-button>
                            <el-button
                              size="mini"
                              type="success"
                              plain
                              @click="performKnowledgeSearch(advancedForm.selectedKnowledgeBases)"
                              icon="el-icon-search"
                            >
                              查询
                            </el-button>
                          </div>
                        </div>
                        <div class="kb-select-tip">
                          <i class="el-icon-info"></i>
                          <span
                            >请选择要搜索的知识库，不选择将搜索所有知识库</span
                          >
                        </div>
                        <el-select
                          v-model="advancedForm.selectedKnowledgeBases"
                          multiple
                          filterable
                          placeholder="请选择要查询的知识库（不选择将搜索所有知识库）"
                          style="width: 100%"
                          class="kb-select"
                        >
                          <el-option
                            v-for="kb in knowledgeBases"
                            :key="kb.name"
                            :label="kb.name"
                            :value="kb.name"
                          >
                            <div class="kb-option">
                              <div class="kb-name">{{ kb.name }}</div>
                              <div class="kb-count">
                                {{ kb.documentCount }}个文档
                              </div>
                            </div>
                          </el-option>
                        </el-select>
                        <div class="kb-selected-info">
                          <span
                            v-if="
                              advancedForm.selectedKnowledgeBases.length === 0
                            "
                            class="no-selection"
                          >
                            <i class="el-icon-warning"></i>
                            未选择知识库，将搜索所有知识库
                          </span>
                          <span v-else>
                            已选择
                            {{ advancedForm.selectedKnowledgeBases.length }}
                            个知识库
                          </span>
                        </div>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 素材整理 -->
        <el-tab-pane label="素材整理" name="materials">
          <div class="materials-container">
            <el-row :gutter="20">
              <el-col :span="16">
                <el-collapse v-model="activeMaterials" accordion>
                  <el-collapse-item title="系统自动收集" name="auto">
                    <template slot="title">
                      <i class="el-icon-magic-stick"></i>
                      系统自动收集 ({{ autoMaterials.length }})
                    </template>
                    <div class="materials-content">
                      <el-table
                        :data="autoMaterials"
                        border
                        style="width: 100%"
                        :row-class-name="tableRowClassName"
                      >
                        <el-table-column prop="title" label="标题" width="200">
                          <template slot-scope="scope">
                            <el-tag
                              size="small"
                              :type="getMaterialTypeColor(scope.row.type)"
                            >
                              {{ getMaterialTypeLabel(scope.row.type) }}
                            </el-tag>
                            <span class="material-title">{{
                              scope.row.title
                            }}</span>
                            <div
                              v-if="
                                scope.row.type === 'knowledge' &&
                                scope.row.similarity
                              "
                              class="similarity-score"
                            >
                              相似度:
                              {{ (scope.row.similarity * 100).toFixed(1) }}%
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="summary"
                          label="摘要"
                          show-overflow-tooltip
                        ></el-table-column>
                        <el-table-column
                          prop="source"
                          label="来源"
                          width="120"
                        ></el-table-column>
                        <el-table-column
                          prop="time"
                          label="时间"
                          width="150"
                        ></el-table-column>
                        <el-table-column label="操作" width="120">
                          <template slot-scope="scope">
                            <div class="table-actions">
                              <el-button
                                size="mini"
                                type="primary"
                                @click="addToManual(scope.row)"
                                icon="el-icon-plus"
                                class="action-btn"
                                >添加</el-button
                              >
                              <el-button
                                size="mini"
                                type="info"
                                @click="previewMaterial(scope.row)"
                                icon="el-icon-view"
                                class="action-btn"
                                >预览</el-button
                              >
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-collapse-item>

                  <el-collapse-item title="手动输入" name="manual">
                    <template slot="title">
                      <i class="el-icon-edit"></i>
                      手动输入
                    </template>
                    <div class="materials-content">
                      <div class="manual-input-container">
                        <div class="input-toolbar">
                          <el-button
                            size="small"
                            @click="clearManualContent"
                            icon="el-icon-delete"
                          >清空</el-button>
                        </div>
                        <el-input
                          type="textarea"
                          :rows="12"
                          v-model="manualContent"
                          placeholder="请输入工作内容，支持Markdown格式&#10;&#10;示例：&#10;### 本周完成工作&#10;- 完成了项目A的开发&#10;- 参加了技术分享会&#10;&#10;### 遇到的问题&#10;- 系统性能优化需要进一步研究&#10;&#10;### 下周计划&#10;- 继续优化系统性能&#10;- 准备下期技术分享"
                        ></el-input>
                        <div class="word-count">
                          字数：{{ manualContent.length }}
                        </div>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-col>

              <el-col :span="8">
                <div class="materials-sidebar">
                  <h4><i class="el-icon-info"></i> 素材统计</h4>
                  <div class="stats-summary">
                    <div class="stat-item">
                      <span class="stat-label">自动收集：</span>
                      <span class="stat-value"
                        >{{ autoMaterials.length }}条</span
                      >
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">手动输入：</span>
                      <span class="stat-value"
                        >{{ manualContent.length }}字</span
                      >
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">总素材：</span>
                      <span class="stat-value"
                        >{{ totalMaterialsCount }}条</span
                      >
                    </div>
                  </div>

                  <h4><i class="el-icon-lightning"></i> 快速操作</h4>
                  <div class="quick-actions">
                    <el-button
                      type="primary"
                      size="small"
                      @click="collectMaterials"
                      :loading="collecting"
                      icon="el-icon-refresh"
                    >
                      重新收集
                    </el-button>
                    <el-button
                      type="success"
                      size="small"
                      @click="exportMaterials"
                      icon="el-icon-download"
                    >
                      导出素材
                    </el-button>
                    <el-button
                      type="warning"
                      size="small"
                      @click="importMaterials"
                      icon="el-icon-upload"
                    >
                      导入素材
                    </el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 报告预览 -->
        <el-tab-pane label="报告预览" name="preview">
          <div class="preview-container">
            <div class="preview-toolbar">
              <div class="toolbar-left">
                <el-button-group>
                  <el-button
                    size="small"
                    @click="copyReport"
                    icon="el-icon-document-copy"
                    :disabled="isEditing"
                    >复制</el-button
                  >
                  <el-button
                    size="small"
                    @click="downloadReport"
                    icon="el-icon-download"
                    :disabled="isEditing"
                    >下载</el-button
                  >
                  <el-button
                    size="small"
                    @click="printReport"
                    icon="el-icon-printer"
                    :disabled="isEditing"
                    >打印</el-button
                  >
                </el-button-group>
              </div>
              <div class="toolbar-right">
                <el-button-group v-if="!isEditing" class="toolbar-btn-group">
                  <el-button
                    size="small"
                    @click="editReport"
                    icon="el-icon-edit"
                    >编辑</el-button
                  >
                  <el-button
                    type="primary"
                    size="small"
                    @click="saveReport"
                    icon="el-icon-check"
                    >保存</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="cancelGeneratedReport"
                    icon="el-icon-close"
                    >取消</el-button>
                </el-button-group>
                <el-button-group v-else>
                  <el-button
                    size="small"
                    @click="undoEdit"
                    icon="el-icon-refresh-left"
                    :disabled="currentHistoryIndex <= 0"
                    >撤销</el-button
                  >
                  <el-button
                    type="warning"
                    size="small"
                    @click="cancelEdit"
                    icon="el-icon-close"
                    >取消</el-button
                  >
                  <el-button
                    type="success"
                    size="small"
                    @click="confirmEdit"
                    icon="el-icon-check"
                    >确认</el-button
                  >
                </el-button-group>
              </div>
            </div>
            <div class="preview-content">
              <div v-if="generatedReport" class="report-preview">
                <!-- 编辑模式 -->
                <div v-if="isEditing" class="edit-mode">
                  <div class="edit-toolbar">
                    <div class="edit-toolbar-left">
                      <el-button-group>
                        <el-button
                          size="small"
                          @click="insertMarkdownToReport('**', '**')"
                          icon="el-icon-bold"
                          >粗体</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertMarkdownToReport('*', '*')"
                          icon="el-icon-italic"
                          >斜体</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertMarkdownToReport('### ', '')"
                          icon="el-icon-title"
                          >标题</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertMarkdownToReport('- ', '')"
                          icon="el-icon-list"
                          >列表</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertMarkdownToReport('[', '](url)')"
                          icon="el-icon-link"
                          >链接</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertMarkdownToReport('```\n', '\n```')"
                          icon="el-icon-document"
                          >代码块</el-button
                        >
                      </el-button-group>
                      <el-divider direction="vertical"></el-divider>
                      <el-button-group>
                        <el-button
                          size="small"
                          @click="insertTable"
                          icon="el-icon-s-grid"
                          >表格</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertImage"
                          icon="el-icon-picture"
                          >图片</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertQuote"
                          icon="el-icon-chat-dot-round"
                          >引用</el-button
                        >
                        <el-button
                          size="small"
                          @click="insertCheckbox"
                          icon="el-icon-check"
                          >复选框</el-button
                        >
                      </el-button-group>
                    </div>
                    <div class="edit-toolbar-right">
                      <el-tag size="small" type="info">
                        字数：{{ editingContent.length }}
                      </el-tag>
                      <el-tag v-if="lastAutoSave" size="small" type="success">
                        自动保存：{{ lastAutoSave }}
                      </el-tag>
                      <el-tag
                        v-if="editHistory.length > 1"
                        size="small"
                        type="warning"
                      >
                        历史记录：{{ editHistory.length - 1 }}
                      </el-tag>
                      <el-tag
                        size="small"
                        :type="isContentChanged ? 'danger' : 'success'"
                      >
                        {{ isContentChanged ? "已修改" : "已保存" }}
                      </el-tag>
                      <el-button
                        size="small"
                        type="text"
                        icon="el-icon-question"
                        @click="showKeyboardHelp"
                        title="快捷键帮助"
                      ></el-button>
                    </div>
                  </div>
                  <div class="edit-container">
                    <div class="edit-panel">
                      <div class="edit-panel-header">
                        <i class="el-icon-edit"></i>
                        <span>编辑区域</span>
                      </div>
                      <el-input
                        type="textarea"
                        v-model="editingContent"
                        :rows="20"
                        placeholder="在此编辑报告内容..."
                        @input="onContentChange"
                        class="edit-textarea"
                      ></el-input>
                    </div>
                    <div class="preview-panel">
                      <div class="preview-panel-header">
                        <i class="el-icon-view"></i>
                        <span>实时预览</span>
                      </div>
                      <div class="preview-panel-content">
                        <markdown-preview
                          :content="editingContent"
                          @error="handlePreviewError"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 预览模式 -->
                <div v-else class="preview-mode">
                  <div class="report-header">
                    <h1 class="report-title">
                      {{
                        reportForm.title ||
                        `${reportForm.type === "weekly" ? "周报" : "月报"}_${
                          reportForm.dateRange[0]
                        }`
                      }}
                    </h1>
                    <div class="report-meta">
                      <span>生成时间：{{ new Date().toLocaleString() }}</span>
                      <span
                        >报告类型：{{
                          reportForm.type === "weekly" ? "周报" : "月报"
                        }}</span
                      >
                      <span
                        >日期范围：{{ reportForm.dateRange[0] }} 至
                        {{ reportForm.dateRange[1] }}</span
                      >
                    </div>
                  </div>
                  <div class="report-body">
                    <markdown-preview
                      :content="generatedReport"
                      @error="handlePreviewError"
                    />
                  </div>
                </div>
              </div>
              <div v-else class="empty-preview">
                <el-empty description="请先收集素材并生成报告">
                  <el-button type="primary" @click="activeTab = 'materials'">
                    去收集素材
                  </el-button>
                </el-empty>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 素材预览对话框 -->
    <el-dialog
      title="素材预览"
      :visible.sync="materialPreviewVisible"
      width="60%"
      :close-on-click-modal="true"
      :append-to-body="true"
      class="material-preview-dialog"
    >
      <div v-if="currentMaterial" class="material-preview-content">
        <h3>{{ currentMaterial.title }}</h3>
        <div class="material-meta">
          <el-tag
            size="small"
            :type="getMaterialTypeColor(currentMaterial.type)"
          >
            {{ getMaterialTypeLabel(currentMaterial.type) }}
          </el-tag>
          <span class="material-time">{{ currentMaterial.time }}</span>
          <span
            v-if="
              currentMaterial.type === 'knowledge' && currentMaterial.similarity
            "
            class="similarity-badge"
          >
            相似度: {{ (currentMaterial.similarity * 100).toFixed(1) }}%
          </span>
        </div>
        <div
          v-if="
            currentMaterial.type === 'knowledge' && currentMaterial.metadata
          "
          class="material-metadata"
        >
          <div class="metadata-item">
            <strong>来源知识库:</strong>
            {{ currentMaterial.metadata.knowledge || "未知" }}
          </div>
          <div v-if="currentMaterial.metadata.filename" class="metadata-item">
            <strong>文件名:</strong> {{ currentMaterial.metadata.filename }}
          </div>
        </div>
        <div class="material-content">
          {{ currentMaterial.summary }}
        </div>
      </div>
    </el-dialog>

    <!-- 导入素材对话框 -->
    <el-dialog
      title="导入素材"
      :visible.sync="importDialogVisible"
      width="40%"
      :close-on-click-modal="true"
      :append-to-body="true"
    >
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleImportFile"
        accept=".json,.txt"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <p>支持的文件格式：</p>
          <ul style="text-align: left; margin: 5px 0;">
            <li><strong>JSON格式</strong>：包含auto（自动素材数组）和manual（手动内容字符串）字段</li>
            <li><strong>纯文本格式</strong>：直接作为手动输入内容导入</li>
          </ul>
          <p style="margin-top: 10px; color: #409eff;">
            <i class="el-icon-info"></i>
            系统会自动识别文件格式，JSON格式会导入素材和内容，纯文本会导入到手动输入区域
          </p>
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
import MarkdownPreview from "@/components/MarkdownPreview";
import request from "@/utils/request";
import {
  listTemplates,
  intelligentCollect,
  generateDraft,
  saveReport,
  getReportStatistics,
  getKnowledgeBaseTags,
  queryKnowledgeBaseContent,
  intelligentKnowledgeSearch,
} from "@/api/report";

// 创建事件总线
const bus = new Vue();

export default {
  name: "IntelligentReport",
  components: { MarkdownPreview },
  data() {
    return {
      activeTab: "config",
      activeMaterials: ["auto", "manual"],
      collecting: false,
      generating: false,
      templates: [],
      autoMaterials: [],
      manualContent: "",
      generatedReport: "",
      materialPreviewVisible: false,
      importDialogVisible: false,
      currentMaterial: null,
      weeklyCount: 0,
      monthlyCount: 0,
      materialsCount: 0,
      totalWeeklyCount: 0,
      totalMonthlyCount: 0,
      reportForm: {
        type: "weekly",
        dateRange: [],
        template: "",
        kbQuery: "",
        title: "",
      },
      advancedForm: {
        selectedKnowledgeBases: [],
        kbQuery: '', // 新增
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      knowledgeBases: [],
      knowledgeSearchResults: [],
      isSearchingKnowledge: false,
      loadingKnowledgeBases: false,
      kbSearchHistory: [],
      showSearchHistory: false,
      // 编辑模式相关
      isEditing: false,
      editingContent: "",
      originalContent: "",
      editHistory: [],
      currentHistoryIndex: -1,
      autoSaveTimer: null,
      lastAutoSave: null,
      keyboardHandler: null,
    };
  },
  computed: {
    totalMaterialsCount() {
      return (
        this.autoMaterials.length + (this.manualContent.length > 0 ? 1 : 0)
      );
    },
    totalKbDocuments() {
      return this.knowledgeBases.reduce(
        (total, kb) => total + kb.documentCount,
        0
      );
    },
    isContentChanged() {
      return this.isEditing && this.editingContent !== this.originalContent;
    },
  },
  created() {
    this.loadTemplates();
    this.loadStatistics();
    this.loadKnowledgeBases();
    this.setupKeyboardShortcuts();
  },
  beforeDestroy() {
    // 清理定时器
    this.stopAutoSave();
    this.removeKeyboardShortcuts();
  },
  methods: {
    async loadTemplates() {
      try {
        const res = await listTemplates();
        if (res.code === 200) {
          this.templates = res.rows;
          if (this.templates.length > 0) {
            this.reportForm.template = this.templates[0].templateId;
          }
        } else {
          this.$message.error(res.msg || "加载模板失败");
        }
      } catch (error) {
        this.$message.error("加载模板失败");
      }
    },

    async loadStatistics() {
      try {
        const res = await getReportStatistics();
        
        if (res.code === 200 && res.data) {
          this.weeklyCount = res.data.weeklyCount || 0;
          this.monthlyCount = res.data.monthlyCount || 0;
          this.materialsCount = res.data.materialsCount || 0;
          this.totalWeeklyCount = res.data.totalWeeklyCount || 0;
          this.totalMonthlyCount = res.data.totalMonthlyCount || 0;
        } else {
          // 使用模拟数据作为备用方案
          this.loadMockStatistics();
        }
      } catch (error) {
        // 使用模拟数据作为备用方案
        this.loadMockStatistics();
      }
    },

    // 加载模拟统计数据
    loadMockStatistics() {
      // 生成一些合理的模拟数据
      this.weeklyCount = 3; // 本周报告数量
      this.monthlyCount = 8; // 本月报告数量
      this.materialsCount = 25; // 素材总数
    },



    onTypeChange() {
      // 根据报告类型调整默认设置
      // 可以在这里添加其他类型相关的逻辑
    },

    async collectMaterials() {
      if (
        !this.reportForm.dateRange ||
        this.reportForm.dateRange.length !== 2
      ) {
        this.$message.error("请先选择日期范围");
        return;
      }

      this.collecting = true;
      try {
        const res = await intelligentCollect({
          dateRange: this.reportForm.dateRange,
        });
        this.autoMaterials = res.data || [];
        this.$message.success(`收集到${this.autoMaterials.length}条素材`);
        this.activeTab = "materials";
      } catch (error) {
        this.$message.error("收集素材失败");
      } finally {
        this.collecting = false;
      }
    },

    async performKnowledgeSearch(selectedKnowledgeBases) {
      this.isSearchingKnowledge = true;
      try {
        if (!this.advancedForm.kbQuery || !this.advancedForm.kbQuery.trim()) {
          this.$message.error("请输入查询关键词");
          this.isSearchingKnowledge = false;
          return;
        }
        const searchOptions = {
          maxResults: 10,
          similarityThreshold: 0.7,
          knowledgeTags: selectedKnowledgeBases,
        };
        // 关键词参数传用户输入
        const res = await intelligentKnowledgeSearch(this.advancedForm.kbQuery, searchOptions);

        // 只要有data就展示，不再判断code
        if (res && res.data) {
          this.knowledgeSearchResults = res.data || [];

          // 将搜索结果转换为素材格式
          const kbMaterials = this.knowledgeSearchResults.map((doc, index) => ({
            id: `kb_${index}`,
            title:
              doc.title ||
              (doc.metadata && doc.metadata.title) ||
              (doc.content
                ? doc.content.slice(0, 20) + (doc.content.length > 20 ? '...': '')
                : "知识库内容片段"),
            summary:
              doc.content ||
              doc.text ||
              (typeof doc.getContent === 'function' ? doc.getContent() : undefined) ||
              (typeof doc.getText === 'function' ? doc.getText() : undefined) ||
              "无内容",
            source: "知识库",
            time: new Date().toLocaleString(),
            type: "knowledge",
            metadata: doc.metadata || (typeof doc.getMetadata === 'function' ? doc.getMetadata() : {}),
            similarity:
              (doc.metadata && doc.metadata.similarity) ||
              (typeof doc.getMetadata === 'function' && doc.getMetadata()?.similarity) ||
              0,
          }));

          // 添加到自动收集的素材中
          this.autoMaterials = [...this.autoMaterials, ...kbMaterials];

          this.$message.success(
            `找到 ${kbMaterials.length} 条相关内容`
          );
          this.activeTab = "materials";
        } else {
          // 只在真正没有数据时提示
          this.$message.warning("未查询到相关内容");
        }
      } catch (error) {
        this.$message.error("查询知识库异常");
      } finally {
        this.isSearchingKnowledge = false;
      }
    },

    addToSearchHistory(query, resultCount) {
      const historyItem = {
        query: query,
        resultCount: resultCount,
        timestamp: new Date().toLocaleString(),
        selectedKBs: [...this.advancedForm.selectedKnowledgeBases],
      };

      // 避免重复添加相同的查询
      const existingIndex = this.kbSearchHistory.findIndex(
        (item) => item.query === query
      );
      if (existingIndex >= 0) {
        this.kbSearchHistory.splice(existingIndex, 1);
      }

      // 添加到历史记录开头
      this.kbSearchHistory.unshift(historyItem);

      // 限制历史记录数量
      if (this.kbSearchHistory.length > 10) {
        this.kbSearchHistory = this.kbSearchHistory.slice(0, 10);
      }
    },

    selectFromHistory(historyItem) {
      this.reportForm.kbQuery = historyItem.query;
      this.advancedForm.selectedKnowledgeBases = [...historyItem.selectedKBs];
    },

    addToManual(material) {
      this.manualContent += `\n\n${material.summary}`;
      this.activeMaterials = ["manual"];
      this.$message.success("已添加到手动输入区域");
    },

    previewMaterial(material) {
      this.currentMaterial = material;
      this.materialPreviewVisible = true;
    },

    clearManualContent() {
      this.$confirm("确定要清空手动输入的内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.manualContent = "";
        this.$message.success("内容已清空");
      });
    },

    exportMaterials() {
      const materials = {
        auto: this.autoMaterials,
        manual: this.manualContent,
        exportTime: new Date().toISOString(),
      };
      const blob = new Blob([JSON.stringify(materials, null, 2)], {
        type: "application/json",
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `materials_${
        new Date().toISOString().split("T")[0]
      }.json`;
      link.click();
      URL.revokeObjectURL(url);
      this.$message.success("素材导出成功");
    },

    importMaterials() {
      this.importDialogVisible = true;
    },

    handleImportFile(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const content = e.target.result;
          
          // 尝试解析为JSON格式
          try {
            const data = JSON.parse(content);
            if (data.auto && Array.isArray(data.auto)) {
              this.autoMaterials = [...this.autoMaterials, ...data.auto];
              this.$message.success(`成功导入 ${data.auto.length} 条自动收集素材`);
            }
            if (data.manual && typeof data.manual === 'string') {
              this.manualContent += "\n\n" + data.manual;
              this.$message.success("成功导入手动输入内容");
            }
            this.$message.success("JSON格式素材导入成功");
            this.importDialogVisible = false;
          } catch (jsonError) {
            // JSON解析失败，当作纯文本处理
            if (content.trim()) {
              this.manualContent += "\n\n" + content;
              this.$message.success("纯文本内容已导入到手动输入区域");
              this.importDialogVisible = false;
            } else {
              this.$message.error("文件内容为空");
            }
          }
        } catch (error) {
          this.$message.error("文件读取失败，请检查文件是否损坏");
        }
      };
      reader.readAsText(file.raw, 'UTF-8');
    },

    async generateDraft() {
      if (!this.reportForm.template) {
        this.$message.error("请选择报告模板");
        return;
      }

      this.generating = true;
      try {
        const res = await generateDraft({
          template: this.reportForm.template,
          reportType: this.reportForm.type,
          dateRange: this.reportForm.dateRange,
          materials: {
            auto: this.autoMaterials,
            manual: this.manualContent,
          },
        });

        if (res.code === 200) {
          this.generatedReport = res.msg;
          this.activeTab = "preview";
          this.$message.success("报告生成成功");
        } else {
          this.$message.error(res.msg || "生成报告失败");
        }
      } catch (error) {
        this.$message.error("生成报告失败");
      } finally {
        this.generating = false;
      }
    },

    previewReport() {
      this.activeTab = "preview";
    },

    editReport() {
      this.isEditing = true;
      this.editingContent = this.generatedReport;
      this.originalContent = this.generatedReport;
      this.editHistory = [this.generatedReport];
      this.currentHistoryIndex = 0;
      this.lastAutoSave = null;

      // 启动自动保存
      this.startAutoSave();
    },

    copyReport() {
      if (!this.generatedReport) return;

      const plainText = this.generatedReport.replace(/<[^>]*>/g, "");
      navigator.clipboard
        .writeText(plainText)
        .then(() => {
          this.$message.success("已复制到剪贴板");
        })
        .catch(() => {
          this.$message.error("复制失败");
        });
    },

    downloadReport() {
      if (!this.generatedReport) return;

      const blob = new Blob([this.generatedReport], { type: "text/markdown" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${
        this.reportForm.title || this.reportForm.type === "weekly"
          ? "周报"
          : "月报"
      }_${this.reportForm.dateRange[0]}.md`;
      link.click();
      URL.revokeObjectURL(url);
      this.$message.success("报告下载成功");
    },

    printReport() {
      if (!this.generatedReport) return;

      const printWindow = window.open("", "_blank");
      printWindow.document.write(`
        <html>
          <head>
            <title>${this.reportForm.title || "报告"}</title>
            <style>
              body { font-family: Arial, sans-serif; margin: 20px; }
              h1 { color: #333; }
              .meta { color: #666; margin-bottom: 20px; }
            </style>
          </head>
          <body>
            <h1>${
              this.reportForm.title ||
              `${this.reportForm.type === "weekly" ? "周报" : "月报"}_${
                this.reportForm.dateRange[0]
              }`
            }</h1>
            <div class="meta">
              生成时间：${new Date().toLocaleString()}<br>
              报告类型：${
                this.reportForm.type === "weekly" ? "周报" : "月报"
              }<br>
              日期范围：${this.reportForm.dateRange[0]} 至 ${
        this.reportForm.dateRange[1]
      }
            </div>
            <div>${this.generatedReport}</div>
          </body>
        </html>
      `);
      printWindow.document.close();
      printWindow.print();
    },

    async saveReport() {
      if (!this.generatedReport) {
        this.$message.error("请先生成报告内容");
        return;
      }

      try {
        const reportData = {
          title:
            this.reportForm.title ||
            `${this.reportForm.type === "weekly" ? "周报" : "月报"}_${
              this.reportForm.dateRange[0]
            }`,
          content: this.generatedReport,
          reportType: this.reportForm.type,
          templateId: this.reportForm.template,
          startDate: this.reportForm.dateRange[0],
          endDate: this.reportForm.dateRange[1],
          materials: {
            auto: this.autoMaterials,
            manual: this.manualContent,
          },
        };

        await saveReport(reportData);

        // 触发事件通知父组件
        bus.$emit("add-to-materials", {
          title: reportData.title,
          summary: reportData.content.substring(0, 100) + "...",
          source: "生成报告",
          time: new Date().toLocaleString(),
          type: "report",
          content: reportData.content,
        });

        this.$message.success("报告已保存");

        // 刷新统计数据
        await this.loadStatistics();

        // 清除报告预览内容
        this.generatedReport = "";
        // 清除素材内容
        this.autoMaterials = [];
        this.manualContent = "";
        // 重置日期范围
        this.reportForm.dateRange = [];
        this.reportForm.title = "";
      } catch (error) {
        this.$message.error("保存报告失败");
      }
    },

    handlePreviewError(error) {
      this.$message.error("报告预览失败");
    },

    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return "even-row";
      }
      return "odd-row";
    },

    getMaterialTypeColor(type) {
      const colorMap = {
        task: "primary",
        meeting: "success",
        document: "warning",
        email: "info",
        knowledge: "danger",
        other: "default",
      };
      return colorMap[type] || "default";
    },

    getMaterialTypeLabel(type) {
      const labelMap = {
        task: "任务",
        meeting: "会议",
        document: "文档",
        email: "邮件",
        knowledge: "知识库",
        other: "其他",
      };
      return labelMap[type] || "其他";
    },

    async loadKnowledgeBases() {
      this.loadingKnowledgeBases = true;
      try {
        const res = await getKnowledgeBaseTags();
        if (res.code === "0000" || res.code === 200) {
          const tags = res.data || [];
          this.knowledgeBases = tags.map((tag) => ({
            name: tag,
            documentCount: 0,
          }));

          // 获取每个知识库的文档数量
          for (let kb of this.knowledgeBases) {
            try {
              const contentRes = await queryKnowledgeBaseContent(kb.name);
              if (
                (contentRes.code === "0000" || contentRes.code === 200) &&
                contentRes.data
              ) {
                kb.documentCount = contentRes.data.length;
              }
            } catch (error) {
              // 获取知识库文档数量失败
            }
          }
        }
      } catch (error) {
        this.$message.error("加载知识库失败");
      } finally {
        this.loadingKnowledgeBases = false;
      }
    },

    selectAllKnowledgeBases() {
      this.advancedForm.selectedKnowledgeBases = this.knowledgeBases.map(
        (kb) => kb.name
      );
    },

    clearKnowledgeBases() {
      this.advancedForm.selectedKnowledgeBases = [];
    },

    clearSearchHistory() {
      this.kbSearchHistory = [];
      this.showSearchHistory = false;
    },

    hideSearchHistory() {
      this.showSearchHistory = false;
    },

    undoEdit() {
      if (this.currentHistoryIndex > 0) {
        this.currentHistoryIndex--;
        this.editingContent = this.editHistory[this.currentHistoryIndex];
      }
    },

    cancelEdit() {
      this.$confirm("确定要取消编辑吗？所有未保存的更改将丢失。", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "继续编辑",
        type: "warning",
      })
        .then(() => {
          this.isEditing = false;
          this.editingContent = this.originalContent;
          this.editHistory = [];
          this.currentHistoryIndex = -1;
          this.stopAutoSave();
          this.lastAutoSave = null;
        })
        .catch(() => {
          // 用户选择继续编辑，不做任何操作
        });
    },

    confirmEdit() {
      this.isEditing = false;
      this.generatedReport = this.editingContent;
      this.originalContent = this.editingContent;
      this.stopAutoSave();
      this.lastAutoSave = null;
      this.$message.success("报告编辑已保存");
    },

    startAutoSave() {
      this.autoSaveTimer = setInterval(() => {
        if (
          this.editingContent !== this.editHistory[this.currentHistoryIndex]
        ) {
          // 添加新的历史记录
          this.editHistory.push(this.editingContent);
          this.currentHistoryIndex = this.editHistory.length - 1;

          // 限制历史记录数量
          if (this.editHistory.length > 50) {
            this.editHistory = this.editHistory.slice(-50);
            this.currentHistoryIndex = this.editHistory.length - 1;
          }

          this.lastAutoSave = new Date().toLocaleTimeString();
        }
      }, 3000); // 每3秒自动保存一次
    },

    stopAutoSave() {
      if (this.autoSaveTimer) {
        clearInterval(this.autoSaveTimer);
        this.autoSaveTimer = null;
      }
    },

    insertMarkdownToReport(prefix, suffix) {
      const textarea = document.querySelector(".edit-textarea textarea");
      if (textarea) {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const selectedText = this.editingContent.substring(start, end);
        const newText =
          this.editingContent.substring(0, start) +
          prefix +
          selectedText +
          suffix +
          this.editingContent.substring(end);
        this.editingContent = newText;
        this.$nextTick(() => {
          textarea.focus();
          textarea.setSelectionRange(
            start + prefix.length,
            end + prefix.length
          );
        });
      }
    },

    onContentChange() {
      // 内容变化时的处理逻辑
      // 这里可以添加实时字数统计、语法检查等功能
    },

    insertTable() {
      const tableTemplate = `| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 内容1 | 内容2 | 内容3 |
| 内容4 | 内容5 | 内容6 |`;
      this.insertTextAtCursor(tableTemplate);
    },

    insertImage() {
      this.$prompt("请输入图片URL", "插入图片", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^https?:\/\/.+/,
        inputErrorMessage: "请输入有效的图片URL",
      })
        .then(({ value }) => {
          const imageMarkdown = `![图片描述](${value})`;
          this.insertTextAtCursor(imageMarkdown);
        })
        .catch(() => {
          // 用户取消
        });
    },

    insertQuote() {
      const quoteTemplate = `> 这是一个引用块
> 可以包含多行内容`;
      this.insertTextAtCursor(quoteTemplate);
    },

    insertCheckbox() {
      const checkboxTemplate = `- [ ] 未完成任务
- [x] 已完成任务`;
      this.insertTextAtCursor(checkboxTemplate);
    },

    insertTextAtCursor(text) {
      const textarea = document.querySelector(".edit-textarea textarea");
      if (textarea) {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const newText =
          this.editingContent.substring(0, start) +
          text +
          this.editingContent.substring(end);
        this.editingContent = newText;
        this.$nextTick(() => {
          textarea.focus();
          textarea.setSelectionRange(start + text.length, start + text.length);
        });
      }
    },

    setupKeyboardShortcuts() {
      this.keyboardHandler = (event) => {
        // Ctrl+S 保存
        if (event.ctrlKey && event.key === "s") {
          event.preventDefault();
          if (this.isEditing) {
            this.confirmEdit();
          } else {
            this.saveReport();
          }
        }
        // Ctrl+Z 撤销
        if (event.ctrlKey && event.key === "z") {
          event.preventDefault();
          if (this.isEditing) {
            this.undoEdit();
          }
        }
        // Esc 取消编辑
        if (event.key === "Escape") {
          if (this.isEditing) {
            this.cancelEdit();
          }
        }
      };
      document.addEventListener("keydown", this.keyboardHandler);
    },

    removeKeyboardShortcuts() {
      if (this.keyboardHandler) {
        document.removeEventListener("keydown", this.keyboardHandler);
      }
    },

    showKeyboardHelp() {
      this.$alert(
        `
        <div style="text-align: left;">
          <h4>编辑快捷键：</h4>
          <ul>
            <li><strong>Ctrl+S</strong> - 保存报告</li>
            <li><strong>Ctrl+Z</strong> - 撤销操作</li>
            <li><strong>Esc</strong> - 取消编辑</li>
          </ul>
          <h4>Markdown语法：</h4>
          <ul>
            <li><strong>**文本**</strong> - 粗体</li>
            <li><strong>*文本*</strong> - 斜体</li>
            <li><strong>### 标题</strong> - 三级标题</li>
            <li><strong>- 项目</strong> - 无序列表</li>
            <li><strong>[链接](URL)</strong> - 超链接</li>
            <li><strong>![描述](图片URL)</strong> - 图片</li>
            <li><strong>> 引用</strong> - 引用块</li>
          </ul>
        </div>
      `,
        "编辑帮助",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "知道了",
        }
      );
    },

    cancelGeneratedReport() {
      this.generatedReport = "";
      this.activeTab = "config";
      this.$message.info("已取消生成的初稿");
    },

  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

/* 统计卡片样式 */
.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.weekly {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.monthly {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.materials {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.templates {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #7f8c8d;
}



/* 主卡片样式 */
.main-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: white;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left i {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.header-actions .el-button-group {
  display: flex;
  align-items: center;
}

.header-actions .el-button-group .el-button {
  margin: 0;
  border-radius: 0;
}

.header-actions .el-button-group .el-button:first-child {
  border-radius: 4px 0 0 4px;
}

.header-actions .el-button-group .el-button:last-child {
  border-radius: 0 4px 4px 0;
}

/* 标签页样式 */
.custom-tabs {
  border: none;
  box-shadow: none;
}

.custom-tabs >>> .el-tabs__header {
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  margin: 0;
}

.custom-tabs >>> .el-tabs__nav-wrap {
  padding: 0 20px;
}

.custom-tabs >>> .el-tabs__item {
  height: 50px;
  line-height: 50px;
  font-weight: 500;
  color: #606266;
}

.custom-tabs >>> .el-tabs__item.is-active {
  color: #409eff;
  background: white;
  border-radius: 8px 8px 0 0;
}

.custom-tabs >>> .el-tabs__content {
  padding: 20px;
  background: white;
  border-radius: 0 0 8px 8px;
}

/* 配置区域样式 */
.config-container {
  padding: 20px 0;
}

.config-form >>> .el-form-item__label {
  font-weight: 500;
  color: #2c3e50;
}

.advanced-config {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.advanced-config h4 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-option {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.template-name {
  font-weight: 500;
  color: #2c3e50;
}

.template-desc {
  font-size: 12px;
  color: #7f8c8d;
}

.kb-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.kb-name {
  font-weight: 500;
  color: #2c3e50;
}

.kb-count {
  font-size: 12px;
  color: #7f8c8d;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 10px;
}

.search-history-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-top: 2px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e9ecef;
  font-weight: 500;
  color: #2c3e50;
}

.history-list {
  max-height: 150px;
  overflow-y: auto;
}

.history-item {
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.history-item:hover {
  background-color: #f8f9fa;
}

.history-query {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #7f8c8d;
}

/* 素材区域样式 */
.materials-container {
  padding: 20px 0;
}

.materials-content {
  padding: 20px 0;
}

.manual-input-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.input-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background: white;
  border-radius: 6px;
}

.word-count {
  text-align: right;
  margin-top: 10px;
  color: #7f8c8d;
  font-size: 12px;
}

.materials-sidebar {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  height: fit-content;
}

.materials-sidebar h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-summary {
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #e9ecef;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: 500;
  color: #409eff;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.quick-actions .el-button {
  width: 100%;
  margin: 0;
  border-radius: 4px;
}

.quick-actions .el-button:not(:last-child) {
  margin-bottom: 5px;
}

/* 表格样式 */
.materials-content >>> .el-table {
  border-radius: 8px;
  overflow: hidden;
}

.materials-content >>> .el-table th {
  background: #f8f9fa;
  color: #2c3e50;
  font-weight: 500;
}

.materials-content >>> .even-row {
  background: #fafbfc;
}

.materials-content >>> .odd-row {
  background: white;
}

.material-title {
  margin-left: 8px;
  color: #2c3e50;
  font-weight: 500;
}

.similarity-score {
  font-size: 11px;
  color: #409eff;
  margin-top: 2px;
  font-weight: 500;
  background: rgba(64, 158, 255, 0.1);
  padding: 2px 4px;
  border-radius: 3px;
  display: inline-block;
}

/* 表格操作按钮样式 */
.materials-content >>> .el-table .el-button {
  margin: 2px;
  border-radius: 4px;
}

.materials-content >>> .el-table .el-button + .el-button {
  margin-left: 5px;
}

/* 表格操作列样式 */
.table-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.action-btn {
  width: 100%;
  margin: 0 !important;
  border-radius: 4px !important;
  font-size: 12px;
  padding: 5px 8px;
  height: 28px;
  line-height: 1;
  min-width: 60px;
}

.action-btn + .action-btn {
  margin-left: 0 !important;
}

/* 预览区域样式 */
.preview-container {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
  overflow: hidden;
}

.preview-toolbar {
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-toolbar .el-button-group {
  display: flex;
  align-items: center;
}

.preview-toolbar .el-button-group .el-button {
  margin: 0;
  border-radius: 0;
}

.preview-toolbar .el-button-group .el-button:first-child {
  border-radius: 4px 0 0 4px;
}

.preview-toolbar .el-button-group .el-button:last-child {
  border-radius: 0 4px 4px 0;
}

.preview-content {
  padding: 0;
  min-height: 500px;
}

.report-preview {
  background: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.report-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  text-align: center;
}

.report-title {
  margin: 0 0 15px 0;
  font-size: 28px;
  font-weight: 600;
}

.report-meta {
  display: flex;
  justify-content: center;
  gap: 30px;
  font-size: 14px;
  opacity: 0.9;
}

.report-body {
  padding: 30px;
}

.empty-preview {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  margin: 20px;
  border-radius: 8px;
}

/* 对话框样式 */
.material-preview-dialog >>> .el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.material-preview-content h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.material-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.material-time {
  color: #7f8c8d;
  font-size: 14px;
}

.material-content {
  line-height: 1.6;
  color: #2c3e50;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
}

.similarity-badge {
  background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%);
  color: #fff;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 8px;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.material-metadata {
  margin: 15px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.metadata-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.metadata-item:last-child {
  margin-bottom: 0;
}

.metadata-item strong {
  color: #2c3e50;
  margin-right: 8px;
  min-width: 80px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-row .el-col {
    margin-bottom: 15px;
  }

  .header-actions {
    flex-direction: column;
    gap: 5px;
  }

  .report-meta {
    flex-direction: column;
    gap: 10px;
  }

  .preview-toolbar {
    flex-direction: column;
    gap: 10px;
  }

  .kb-stats-content {
    flex-direction: column;
    gap: 8px;
  }

  .kb-stat-item {
    text-align: left;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .kb-stat-item .stat-label {
    margin-bottom: 0;
  }

  .history-meta {
    flex-direction: column;
    gap: 2px;
  }

  .table-actions {
    flex-direction: row;
    gap: 2px;
  }

  .action-btn {
    width: auto;
    min-width: 50px;
  }

  .kb-stats-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .refresh-btn {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .advanced-config {
    padding: 15px;
  }

  .kb-stats-card {
    padding: 12px;
  }
}

/* 知识库统计卡片样式 */
.kb-stats-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.kb-stats-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #2c3e50;
  font-weight: 500;
}

.kb-stats-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.kb-stats-title i {
  color: #409eff;
  font-size: 16px;
}

.refresh-btn {
  border-radius: 6px;
  font-size: 12px;
  padding: 6px 12px;
  height: 28px;
  line-height: 1;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.kb-stats-content {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.kb-stat-item {
  text-align: center;
  flex: 1;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
}

.kb-stat-item .stat-label {
  display: block;
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.kb-stat-item .stat-value {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

/* 知识库搜索和选择样式 */
.kb-search-container {
  position: relative;
}

.kb-search-input {
  position: relative;
}

.kb-select-container {
  position: relative;
}

.kb-select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.kb-select-title {
  font-weight: 500;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.kb-select-title::before {
  content: "📚";
  font-size: 14px;
}

.kb-select-actions {
  display: flex;
  gap: 6px;
}

.kb-select-actions .el-button {
  border-radius: 4px;
  font-size: 12px;
  padding: 4px 8px;
  height: 24px;
  line-height: 1;
  min-width: 50px;
}

.kb-select {
  margin-bottom: 8px;
}

.kb-select >>> .el-select__tags {
  max-width: calc(100% - 30px);
}

.kb-select-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  font-size: 12px;
  color: #409eff;
}

.kb-select-tip i {
  color: #409eff;
  font-size: 14px;
}

.kb-selected-info {
  text-align: right;
  margin-top: 8px;
  color: #7f8c8d;
  font-size: 12px;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.no-selection {
  color: #e6a23c;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.no-selection i {
  color: #e6a23c;
  font-size: 14px;
}

/* 编辑模式样式 */
.edit-mode {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.edit-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.edit-toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.edit-toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.edit-container {
  display: flex;
  height: 600px;
}

.edit-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e9ecef;
}

.edit-panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 500;
  color: #2c3e50;
}

.edit-panel-header i {
  color: #409eff;
}

.edit-textarea {
  flex: 1;
  border: none;
  border-radius: 0;
}

.edit-textarea >>> .el-textarea__inner {
  border: none;
  border-radius: 0;
  resize: none;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 14px;
  line-height: 1.6;
  padding: 20px;
  background: #fafbfc;
}

.edit-textarea >>> .el-textarea__inner:focus {
  border: none;
  box-shadow: none;
  background: white;
}

.preview-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.preview-panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 500;
  color: #2c3e50;
}

.preview-panel-header i {
  color: #67c23a;
}

.preview-panel-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: white;
}

.preview-panel-content >>> .markdown-preview {
  max-width: none;
}

.preview-panel-content >>> .markdown-preview h1,
.preview-panel-content >>> .markdown-preview h2,
.preview-panel-content >>> .markdown-preview h3,
.preview-panel-content >>> .markdown-preview h4,
.preview-panel-content >>> .markdown-preview h5,
.preview-panel-content >>> .markdown-preview h6 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #2c3e50;
}

.preview-panel-content >>> .markdown-preview p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.preview-panel-content >>> .markdown-preview ul,
.preview-panel-content >>> .markdown-preview ol {
  margin-bottom: 10px;
  padding-left: 20px;
}

.preview-panel-content >>> .markdown-preview li {
  margin-bottom: 5px;
}

.preview-panel-content >>> .markdown-preview code {
  background: #f1f3f4;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 13px;
}

.preview-panel-content >>> .markdown-preview pre {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 10px 0;
}

.preview-panel-content >>> .markdown-preview pre code {
  background: none;
  padding: 0;
}

.preview-panel-content >>> .markdown-preview blockquote {
  border-left: 4px solid #409eff;
  padding-left: 15px;
  margin: 10px 0;
  color: #666;
  background: #f8f9fa;
  padding: 10px 15px;
  border-radius: 0 6px 6px 0;
}

.preview-panel-content >>> .markdown-preview table {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
}

.preview-panel-content >>> .markdown-preview th,
.preview-panel-content >>> .markdown-preview td {
  border: 1px solid #e9ecef;
  padding: 8px 12px;
  text-align: left;
}

.preview-panel-content >>> .markdown-preview th {
  background: #f8f9fa;
  font-weight: 500;
}

/* 编辑模式响应式设计 */
@media (max-width: 1200px) {
  .edit-container {
    flex-direction: column;
    height: auto;
  }

  .edit-panel {
    border-right: none;
    border-bottom: 1px solid #e9ecef;
  }

  .edit-textarea >>> .el-textarea__inner {
    min-height: 300px;
  }

  .preview-panel-content {
    min-height: 400px;
  }
}

@media (max-width: 768px) {
  .edit-toolbar {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .edit-toolbar-left {
    justify-content: center;
  }

  .edit-toolbar-right {
    justify-content: center;
  }

  .edit-textarea >>> .el-textarea__inner {
    min-height: 250px;
    font-size: 13px;
    padding: 15px;
  }

  .preview-panel-content {
    min-height: 300px;
    padding: 15px;
  }
}

/* 高级配置区按钮字体颜色始终为白色，仅刷新和全选 */
.refresh-btn,
.kb-select-actions .el-button--primary {
  color: #fff !important;
}

/* 工具栏按钮组间距统一 */
.toolbar-btn-group .el-button {
  margin-right: 8px !important;
  height: 32px;
  min-width: 64px;
  box-sizing: border-box;
}
.toolbar-btn-group .el-button:last-child {
  margin-right: 0 !important;
}

</style>